package com.kjlink.internal.report4vue.config;

import cn.dev33.satoken.exception.NotLoginException;
import cn.xuqiudong.common.base.enums.CommonMsgEnum;
import cn.xuqiudong.common.base.exception.BadParamException;
import cn.xuqiudong.common.base.exception.CommonException;
import cn.xuqiudong.common.base.exception.UnauthorizedException;
import cn.xuqiudong.common.base.model.BaseResponse;
import cn.xuqiudong.common.base.web.GlobalExceptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 描述:
 *
 * @author Vic.xu
 * @since 2024-11-26 17:52
 */
@RestControllerAdvice(basePackages = "com.kjlink.internal.report4vue")
public class ApiGlobalExceptionHandler {

    protected static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    protected static final String ERROR_PAGE = "error/500";


    @ExceptionHandler({UnauthorizedException.class})
    public ResponseEntity<String> unauthorizedHandler(HttpServletRequest request, UnauthorizedException e) {
        logger.error("无访问{}权限", request.getRequestURI());
        return new ResponseEntity<>(e.getMessage(), HttpStatus.UNAUTHORIZED);
    }

    @ExceptionHandler({NotLoginException.class})
    public ResponseEntity<String> notLoginException(HttpServletRequest request, NotLoginException e) {
        logger.error("token失效", e);
        return new ResponseEntity<>(e.getMessage(), HttpStatus.UNAUTHORIZED);
    }


    @ExceptionHandler({CommonException.class})
    public BaseResponse commonHandler(HttpServletRequest request, CommonException e) {
        logger.error("通用异常", e);
        return BaseResponse.error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler({BadParamException.class})
    public BaseResponse badParamHandler(HttpServletRequest request, BadParamException e) {
        logger.error("请求参数绑定异常", e);
        String msg = CommonMsgEnum.PARAM_ERROR.getMsg();
        if (e.isValidated()) {
            msg = e.getMessage();
        }
        return BaseResponse.error(CommonMsgEnum.PARAM_ERROR.getCode(), msg);
    }

    @ExceptionHandler({Exception.class})
    public BaseResponse exceptionHandler(HttpServletRequest request, Exception e) {
        logger.error("非自定义异常", e);
        return BaseResponse.error(e.getMessage());
    }


}
